package com.bz.zuul.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

@Component
public class RateLimitFilter extends ZuulFilter {

    private static final RateLimiter rateLimiter = RateLimiter.create(1);

    private final static String NEXT = "next";// 值为 boolean ，表示是否执行往下执行 run 方法

    RequestContext context;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }


    @Override
    public int filterOrder() {
        return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 1;
    }


    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return (boolean) ctx.getOrDefault(NEXT,true);
    }


    @Override
    public Object run() throws ZuulException {
        context = RequestContext.getCurrentContext();

        //是否能从令牌桶中获取到令牌
        if (!rateLimiter.tryAcquire()){
            return fail(429,"error: rate limit");
        }
        return null;
    }

    // 定义不通过的方法
    Object fail(int code,String message){
        context.set(NEXT, false);
        context.setSendZuulResponse(false);// 不往下执行了
        context.getResponse().setContentType("text/html;charset=utf-8");
        context.setResponseStatusCode(code);
        context.setResponseBody(String.format("{\"result\":\"%s!\"}",message));
        return null;
    }

    // 定义成功的方法
    Object success(){
        context.set(NEXT,true);
        return null;
    }
}
